<template>
  <div style="display: flex">
    <div style="z-index: 999; margin-top: 100px; width: 50px">
      <el-button
        size="mini"
        type="primary"
        icon="el-icon-arrow-left"
        @click="timeadd"
      ></el-button>
    </div>
    <div class="p_chart" ref="lamp_freezedata"></div>
    <div style="z-index: 999; margin-top: 100px; width: 50px">
      <el-button
        size="mini"
        type="primary"
        icon="el-icon-arrow-right"
        @click="timereduce"
      ></el-button>
    </div>
  </div>
</template>

<script>
import { deviceElectricalHistory } from "@/api/iot/deviceLog";
import FileSaver from "file-saver";
import XLSX from "xlsx";
const querydays = [1, 7, 15, 30];
export default {
  props: {
    lampfreezedata: {
      type: Object,
    },
  },
  name: "lampfreezedata",
  data() {
    return {
      timeslot: {
        starttime: "",
        endtime: "",
      },
      data: [],
      querydaynum: 0,
      freezedata: {
        //  time:['2019-10-10', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17', '2019-10-11', '2019-10-12', '2019-10-13', '2019-10-14', '2019-10-15', '2019-10-17'],
        //  current:[1, 2, 2, 3, 2, 1, 4],
        // voltage:[220.5, 224.2, 221.3, 219.8, 218.2, 220.3, 223.0],
        //  temp:[10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 16.2]
        time: [],
        current: [],
        voltage: [],
        temp: [],
      },
    };
  },
  created() {},
  mounted() {
    this.refreshdata();
  },
  methods: {
    cal_timeslot(daynum, date) {
      var end = new Date(date);
      var start = new Date(date);
      start.setTime(start.getTime() - 3600 * 1000 * 24 * daynum);
      this.timeslot.endtime = this.FormatDate(end, "yyyy-MM-dd");
      this.timeslot.starttime = this.FormatDate(start, "yyyy-MM-dd");
    },
    timeadd() {
      this.querydaynum++;
      if (this.querydaynum < querydays.length) {
        this.refreshdata();
      } else {
        this.querydaynum = querydays.length - 1;
      }
    },
    timereduce() {
      if (this.querydaynum > 0) {
        this.querydaynum--;
        this.refreshdata();
      }
    },
    isCloseEnough(newTime, timeList, thresholdSeconds) {
    for (let time of timeList) {
      let temp = new Date(time).getTime();
      let tmep2 = new Date(newTime).getTime();
        if (Math.abs(temp - tmep2) < thresholdSeconds * 1000) {
            return true; // 如果存在相近的时间戳，则返回 true
        }
    }
    return false; // 如果没有相近的时间戳，则返回 false
},
    isCheckTime(newTime, timeList, thresholdSeconds){
      if(timeList.includes(newTime)){
        return newTime;
      }
      for (let time of timeList) {
      let temp = new Date(time).getTime();
      let tmep2 = new Date(newTime).getTime();
        if (Math.abs(temp - tmep2) <= thresholdSeconds * 1000) {
            return time;
        }
    }
    },
    refreshdata() {
      this.freezedata = {
        time: [],
        current: [],
        voltage: [],
        temp: [],
      };

      if (
        this.lampfreezedata.collectionTime != null &&
        this.lampfreezedata.collectionTime != ""
      ) {
        this.cal_timeslot(
          querydays[this.querydaynum],
          this.lampfreezedata.collectionTime
        ); //查询1天数据
      }else{
        let date = new Date()
        this.cal_timeslot(
          querydays[this.querydaynum],
          date
        ); 
      }

      var that = this;
      var data = {};
      data.serialNumber = that.lampfreezedata.serialNumber;
      data.beginTime = that.timeslot.starttime;
      data.endTime = that.timeslot.endtime;

      deviceElectricalHistory(data).then((res) => {
        if (res.code == 200) {
          // 初始化数据对象
          let dataMap = {
            DRA_Current: { name: "current", values: new Array() },
            DRA_Voltage: { name: "voltage", values: new Array() },
            DRA_Temp: { name: "temp", values: new Array() },
          };

          // 组合时间戳和数据值
          res.rows.forEach((item) => {
            if (item.thingsModelName in dataMap) {
              let data = dataMap[item.thingsModelName];
              for (let i = 0; i < item.total; i++) {
                let timestamp = item.list[i].datatime;
                let value = item.list[i].thingsModelvalue;
                data.values.push({ timestamp, value });
              }
            }
          });

          // 生成时间列表并填充数据
          let timeList = [];
          dataMap["DRA_Current"].values.forEach((currentItem) => {
            timeList.push(currentItem.timestamp);
            that.freezedata.current.push(currentItem.value);
          });
          dataMap["DRA_Voltage"].values.forEach((voltageItem) => {
            if (!that.isCloseEnough(voltageItem.timestamp,timeList,3)) {
              timeList.push(voltageItem.timestamp);
              that.freezedata.voltage.push(null);
              that.freezedata.current.push(null);
            }
            that.freezedata.voltage[timeList.indexOf(that.isCheckTime(voltageItem.timestamp,timeList,1))] =
              voltageItem.value;
          });
          dataMap["DRA_Temp"].values.forEach((tempItem) => {
            if (!that.isCloseEnough(tempItem.timestamp,timeList,3)) {
              timeList.push(tempItem.timestamp);
              that.freezedata.temp.push(null); 
              that.freezedata.voltage.push(null);
              that.freezedata.current.push(null);
            }
            that.freezedata.temp[timeList.indexOf(that.isCheckTime(tempItem.timestamp,timeList,1))] =
              tempItem.value;
          });

          // 去重时间列表
          timeList = [...new Set(timeList)];
          that.freezedata.time = timeList;
          that.series = [
            {
              //name: '电压',
              name: sessionStorage.lang == "zh-cn" ? "电压" : "Voltage",
              type: "line",
              data: that.freezedata.voltage,
              unit: "V",
            },
            {
              //name: '电流',
              name: sessionStorage.lang == "zh-cn" ? "电流" : "Current",
              type: "line",
              data: that.freezedata.current,
              unit: "A",
            },
            {
              //name: '温度',
              name: sessionStorage.lang == "zh-cn" ? "温度" : "Temperature",
              type: "line",
              yAxisIndex: 1,
              data: that.freezedata.temp,
              unit: "℃",
            },
          ];
          let myChart = that.$echarts.init(that.$refs.lamp_freezedata);
          myChart.clear();
          let option = {
            tooltip: {
              trigger: "axis",
              formatter: function (params) {
                var relVal = params[0].name;
                debugger;
                for (var i = 0, l = params.length; i < l; i++) {
                  if (params[i].value != undefined && params[i].value !="") {
                    relVal +=
                      "<br/>" +
                      params[i].marker +
                      params[i].seriesName +
                      " : " +
                      params[i].value +
                      that.series[params[i].seriesIndex].unit;
                  }
                }
                return relVal;
              },
              axisPointer: {
                type: "cross",
                crossStyle: {
                  color: "#999",
                },
              },
            },
            legend: {
              //data: ['电压', '电流', '温度']
              data:
                sessionStorage.lang == "zh-cn"
                  ? ["电压", "电流", "温度"]
                  : ["Voltage", "Current", "Temperature"],
            },
            grid: {
              left: "1%",
              right: "1%",
              bottom: "1%",
              containLabel: true,
            },
            toolbox: {
              show: true,
              feature: {
                dataZoom: {
                  yAxisIndex: "none",
                  title: {
                    zoom:
                      sessionStorage.lang == "zh-cn" ? "区域缩放" : "Area Zoom",
                    back:
                      sessionStorage.lang == "zh-cn"
                        ? "区域缩放还原"
                        : "Area Zoom Restore",
                  }
                },
                dataView: {
                  readOnly: false,
                  show: true,
                  //readOnly: true,
                  lang:
                    sessionStorage.lang == "zh-cn"
                      ? ["数据视图", "关闭", "导出Excel"]
                      : ["Data View", "Close", "Export to Excel"],
                  title:
                    sessionStorage.lang == "zh-cn" ? "数据视图" : "Data View",
                    optionToContent: function (opt) {
                    var axisData = opt.xAxis[0].data;
                    var series = opt.series;
                    var tdHeads =
                      '<td  style="padding:0 10px;">' +
                      that.$t(
                        "title.tunnellightingsystem_systemmanagement_title_pointoftime"
                      ) +
                      "</td>";
                    series.forEach(function (item) {
                      tdHeads +=
                        '<td style="padding: 0 10px;">' +
                        item.name +
                        "</td>";
                    });
                    var table =
                      '<table border="1" style="margin-left:20px;border-collapse:collapse;font-size:14px;text-align:center;"><tbody><tr>' +
                      tdHeads +
                      "</tr>";
                    var tdBodys = "";
                    for (var i = 0, l = axisData.length; i < l; i++) {
                      for (var j = 0; j < series.length; j++) {
                        if (typeof series[j].data[i] == "object") {
                          tdBodys += "<td>" + series[j].data[i] + "</td>";
                        } else {
                          tdBodys += "<td>" + series[j].data[i] + "</td>";
                        }
                      }
                      table +=
                        '<tr><td style="padding: 0 10px>' +
                        axisData[i] +
                        "</td>" +
                        tdBodys +
                        "</tr>";
                      tdBodys = "";
                    }
                    table += "</tbody></table>";
                    return table;
                  },
                  contentToOption: function (HTMLDomElement, opt) {
                    var that = this;
                    let et = XLSX.utils.table_to_book(
                      document.getElementById("Mytable"),
                      { raw: true }
                    );
                    let etout = XLSX.write(et, {
                      bookType: "xlsx",
                      bookSST: true,
                      type: "array",
                    });

                    try {
                      FileSaver.saveAs(
                        new Blob([etout], {
                          type: "application/octet-stream",
                        }),
                        "lampfreezedata.xlsx"
                      );
                    } catch (e) {}
                    return etout;
                  },
                },
                magicType: {
                  type: ["line", "bar"],
                  title: {
                    //line:'切换为折线图',
                    line:
                      sessionStorage.lang == "zh-cn"
                        ? "切换为折线图"
                        : "Switch to line chart",
                    //bar:'切换为柱状图'
                    bar:
                      sessionStorage.lang == "zh-cn"
                        ? "切换为柱状图"
                        : "Switch to bar chart",
                  },
                },
                restore: {
                  //title:'还原'
                  title: sessionStorage.lang == "zh-cn" ? "还原" : "Revert",
                },
                saveAsImage: {
                  title:
                    sessionStorage.lang == "zh-cn"
                      ? "保存为图片"
                      : "Save As Image",
                },
              },
            },
            xAxis: {
              type: "category",
              boundaryGap: true,
              data: that.freezedata.time,
            },
            yAxis: [
              {
                type: "value",
                nameTextStyle: {
                  padding: [0, 0, 0, 100],
                },
                //name: '       电参数',
                name:
                  sessionStorage.lang == "zh-cn"
                    ? "电参数"
                    : "Electrical Parameters",
                axisLabel: {
                  formatter: "{value}",
                },
              },
              {
                type: "value",
                //name: '温度',
                name: sessionStorage.lang == "zh-cn" ? "温度" : "Temperature",
                min: 0,
                max: 100,
                interval: 10,
                axisLabel: {
                  formatter: "{value} °C",
                },
              },
            ],
            dataZoom: [
              {
                type: "inside",
                xAxisIndex: 0,
                minSpan: 5,
              },
            ],
            series: that.series,
          };
          myChart.setOption(option);
        }
      });
    },
  },
};
</script>
<style scoped>
.p_chart {
  flex: 1;
  height: 200px;
  padding: 1px 2px;
  margin-top: 1px;
}
</style>
